import RPi.GPIO as GPIO
import time
import PCF8591 as ADC

'''
+-加3条线  + 5v
sw:g27
dt:g18
clk:g17
'''

clkpin = 11     #clk
dtpin = 12     #dt
Btnpin = 13     #sw 按下清零

g_count = 0     #计数 值

RoFlag = 0      #是否发生旋转标志
Last_RobStatus=0     #dt 状态
Cur_RobStatus=1     #clk状态

def btnisr():
    global g_count
    g_count=0


def makerobo_setup():
    GPIO.setmode(GPIO.BOARD)  # 采用物理编号
    GPIO.setwarnings(False)  # 去除GPIO的警告
    GPIO.setup(clkpin, GPIO.IN)
    GPIO.setup(dtpin, GPIO.IN)
    GPIO.setup(Btnpin, GPIO.IN,pull_up_down=GPIO.PUD_UP)    #上拉输入
    # 初始化中断函数  使能按钮的下降沿中断
    GPIO.add_event_detect(Btnpin,GPIO.FALLING,callback=btnisr)

def rotateDeal():
    global RoFlag
    global Last_RobStatus
    global Cur_RobStatus
    global g_count

    Last_RobStatus = GPIO.input(dtpin)
    while(not GPIO.input(clkpin)):  #判断clk 电平变化来区分方向
        Cur_RobStatus = GPIO.input(dtpin)
        RoFlag = 1      #发生旋转
    if RoFlag==1:
        RoFlag=0
        if(Last_RobStatus==0) and (Cur_RobStatus==1):
            g_count+=1      #逆时针 +1
        if(Last_RobStatus==1) and (Cur_RobStatus==0):
            g_count -= 1  # 顺时针 -1


def loop():
    global g_count
    tmp=0
    while True:
        rotateDeal()        #方向判断
        if tmp!=g_count:
            print("g_count=%d"%g_count)
            g_count=tmp


def destroy(): #释放资源
    GPIO.cleanup()

if __name__=='__main__':
    try:
        loop()
    except KeyboardInterrupt:   #按下 ctrl+c 释放资源
        destroy()